package charlie.com.courier;

import charlie.shop.misc.Common;
import com.charlie.beans.Product;
import com.charlie.beans.ShipmentOrder;
import com.charlie.beans.SoHistory;
import com.charlie.beans.SoProduct;
import com.charlie.beans.Users;
import com.charlie.mail.MailLocal;
import com.charlie.mail.MailTemplate;
import com.charlie.mail.MailTemplateType;
import com.charlie.sessions.ShipmentOrderFacadeLocal;
import com.charlie.sessions.SoHistoryFacadeLocal;
import com.charlie.sessions.StatusDictFacadeLocal;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * View, edit current order information servlet
 * 
 * @author Alexandra
 */
@WebServlet(name = "OrderItemForCourier", urlPatterns = {"/courier/order/*"})
public class OrderItemForCourier extends HttpServlet {

    
    private static final Integer SHIPPING_STATUS = 2;
    @EJB
    private ShipmentOrderFacadeLocal order;
    @EJB
    private StatusDictFacadeLocal status;
    @EJB
    private SoHistoryFacadeLocal historyItem;
    @EJB
    private MailLocal mail;

    /**
     * Process order editing
     * 
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        /**
         * Holds number of products in the order
         */
        Map<Product, Integer> prList = new HashMap<Product, Integer>();
        ShipmentOrder currentOrder = null;

        int orderId = Common.getParametrInt(request, "idOfOrder");
        if (orderId > 0) {
            prList.clear();
            currentOrder = order.find(orderId);
            List<SoHistory> history = new ArrayList<SoHistory>();
            for (SoHistory s: currentOrder.getSoHistoryCollection() )
            { history.add(s);}
            if (history.get(history.size()-1).getStatusDictId().getStatusDictId().equals(SHIPPING_STATUS)){
           try {
                request.setAttribute("order", currentOrder);
                for (SoProduct s : currentOrder.getSoProductCollection()) {
                    prList.put(s.getProductId(), s.getAmount());
                }
            } catch (Exception ex) {
            }
            request.setAttribute("productsList", prList);
        
            SoHistory soHistory = new SoHistory();
            String comment = request.getParameter("commentForOrder");
            if (comment != null) {
                soHistory.setCommentary(comment);
            }

            if (request.getParameter("ship") != null) {
                soHistory.setChangeDate(new Date());
                soHistory.setSoId(currentOrder);

                HttpSession session = (HttpSession) request.getSession(true);
                Users user = (Users) session.getAttribute("user");
                if (user != null) {
                    soHistory.setUserId(user);
                }

                soHistory.setStatusDictId(status.find(3));
               try{
                   historyItem.create(soHistory);
               }catch (Exception e){}

                response.sendRedirect(request.getContextPath() + "/courier/orders");
                if (currentOrder.getIsSubscribed() == 1) {
                    MailTemplate tpl = new MailTemplate(MailTemplateType.COURIER_ACCEPT);
                    mail.send(currentOrder.getEmail(), "CharlieShop: order delivered", tpl);
                }
                return;
            }}
           else{}
        }
        request.getRequestDispatcher("/courier/orderItemForCourier.jsp").forward(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }    
}
